'''
Author: SimonCK666 SimonYang223@163.com
Date: 2022-05-13 16:28:13
LastEditors: SimonCK666 SimonYang223@163.com
LastEditTime: 2022-05-18 21:56:49
FilePath: \\tao-bao-crawler\\analysis.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
'''
Function:
    淘宝商品数据可视化, pyecharts版本: 1.5.1
Author:
    Simon
'''
import os
import pickle
from pyecharts import options
from pyecharts.globals import ThemeType
from pyecharts.charts import Bar, Page, Pie, Map


'''检查文件在是否存在'''
def checkDir(dirpath):
    if not os.path.exists(dirpath):
        os.mkdir(dirpath)
        return False
    return True


'''画饼图'''
def drawPie(title, data, savedir='./results'):
    checkDir(savedir)
    pie = (Pie(init_opts=options.InitOpts(theme=ThemeType.VINTAGE))
          .add('', [list(item) for item in data.items()], radius=['30%', '75%'], center=['50%', '50%'], rosetype='radius')
          .set_global_opts(title_opts=options.TitleOpts(title=title, pos_left='center'), legend_opts=options.LegendOpts(orient='vertical', pos_top='5%', pos_left='2%')))
    pie.render(os.path.join(savedir, title+'.html'))


'''画柱状图'''
def drawBar(title, data, savedir='./results'):
    checkDir(savedir)
    bar = (Bar(init_opts=options.InitOpts(theme=ThemeType.VINTAGE))
          .add_xaxis(list(data.keys()))
          .add_yaxis('', list(data.values()))
          .set_global_opts(xaxis_opts=options.AxisOpts(axislabel_opts=options.LabelOpts(rotate=-25)),
                           title_opts=options.TitleOpts(title=title, pos_left='center'), legend_opts=options.LegendOpts(orient='vertical', pos_top='15%', pos_left='2%')))
    bar.render(os.path.join(savedir, title+'.html'))


'''画地图'''
def drawMap(title, data, savedir='./results'):
    checkDir(savedir)
    map_ = (Map(init_opts=options.InitOpts(theme=ThemeType.ROMANTIC))
           .add('', [list(item) for item in data.items()], 'china')
           .set_global_opts(title_opts=options.TitleOpts(title=title, pos_left='center'), visualmap_opts=options.VisualMapOpts(max_=max(list(data.values())), min_=min(list(data.values())), is_show=True)))
    map_.render(os.path.join(savedir, title+'.html'))


'''run'''
if __name__ == '__main__':
    goods_infos_dict = pickle.load(open('乐器小号.pkl', 'rb'))
    # 淘宝上卖乐器小号的商家在全国范围内的数量​分布情况
    data = {}
    for key, value in goods_infos_dict.items():
        location = value['location'].split(' ')[0]
        if location in data:
            data[location] += 1
        else:
            data[location] = 1
    drawMap(title='淘宝上卖乐器小号的商家在全国范围内的数量​分布情况', data=data)
    # 淘宝上卖乐器小号的​店铺的销量排名前10
    data = {}
    for key, value in goods_infos_dict.items():
        num_sells = value['num_sells']
        if not num_sells:
           continue
        if u'万' in num_sells:
            num_sells = float(num_sells.replace(u'万+人付款', '').strip()) * 1e4
        else:
            num_sells = float(num_sells.replace(u'人付款', '').replace(u'+', '').strip())
        if value['shope_name'] in data:
            data[value['shope_name']] += num_sells
        else:
            data[value['shope_name']] = num_sells
    data = dict(sorted(data.items(), key=lambda item: item[1])[-10:])
    drawBar('淘宝上卖乐器小号的​店铺的销量排名前10', data)
    # 淘宝上评论数量前10名的乐器小号店铺
    data = {}
    for key, value in goods_infos_dict.items():
        num_comments = value['num_comments']
        if not num_comments:
           continue
        num_comments = float(num_comments)
        if value['shope_name'] in data:
            data[value['shope_name']] += num_comments
        else:
            data[value['shope_name']] = num_comments
    data = dict(sorted(data.items(), key=lambda item: item[1])[-10:])
    drawBar('淘宝上评论数量前10名的乐器小号店铺', data)
    # 要运费与免运费的乐器小号相关商品比例
    data = {'fee': 0, 'no_fee': 0}
    for key, value in goods_infos_dict.items():
        if float(value['fee']) > 0:
            data['fee'] += 1
        else:
            data['no_fee'] += 1
    drawPie('要运费与免运费的乐器小号相关商品比例', data)
    # 乐器小号相关商品的售价区间
    data = {'小于1000元': 0, '1000~2000元': 0, '2000~3000元': 0, '3000~4000元': 0, '4000~5000元': 0, '5000~10000元': 0, '10000元以上': 0}

    # print(len(goods_infos_dict))
    total_goods = len(goods_infos_dict)

    for key, value in goods_infos_dict.items():
        if not value['price']:
            continue
        price = float(value['price'])
        if price < 1000:
            data['小于1000元'] += 1
        # elif price >= 100 and price <= 200:
        #     data['100~200元'] += 1
        # elif price > 200 and price <= 300:
        #     data['200~300元'] += 1
        # elif price > 300 and price <= 500:
        #     data['300~500元'] += 1
        # elif price > 500 and price <= 800:
        #     data['500~800元'] += 1
        # elif price > 800 and price <= 1000:
        #     data['800~1000元'] += 1
        if price >= 1000 and price <= 2000:
            data['1000~2000元'] += 1
        elif price > 2000 and price <= 3000:
            data['2000~3000元'] += 1
        elif price > 3000 and price <= 4000:
            data['3000~4000元'] += 1
        elif price > 4000 and price <= 5000:
            # print(price)
            data['4000~5000元'] += 1
        elif price > 5000 and price <= 10000:
            data['5000~10000元'] += 1
        elif price > 10000:
            data['10000元以上'] += 1
        
    # 乐器小号相关商品的售价区间
    # xiaohao，xiaojungu
    # data = {'小于50元': 0,  '50~80元': 0, '80~100元': 0, '100~200元': 0, '200~300元': 0, '300~500元': 0, '500~800元': 0, '800~1000元': 0, '1000元以上': 0}

    # # print(len(goods_infos_dict))
    # total_goods = len(goods_infos_dict)

    # for key, value in goods_infos_dict.items():
    #     if not value['price']:
    #         continue
    #     price = float(value['price'])
    #     if price < 50:
    #         data['小于50元'] += 1
    #     elif price >= 50 and price <= 80:
    #         data['50~80元'] += 1
    #     elif price >= 80 and price <= 100:
    #         data['80~100元'] += 1
    #     elif price >= 100 and price <= 200:
    #         data['100~200元'] += 1
    #     elif price > 200 and price <= 300:
    #         data['200~300元'] += 1
    #     elif price > 300 and price <= 500:
    #         data['300~500元'] += 1
    #     elif price > 500 and price <= 800:
    #         data['500~800元'] += 1
    #     elif price > 800 and price <= 1000:
    #         data['800~1000元'] += 1
    #     else:
    #         data['1000元以上'] += 1
    # print(data)
    # for g_k in data:
    #     # print(data[g_k])
    #     # print(data[g_k] / total_goods)
    #     data[g_k] = data[g_k] / total_goods * 100
    #     # print(data[g_k])


    drawPie('乐器小号相关商品的售价区间', data)